﻿using ITSM.Model;
using ITSM.Model.Entity;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ITSM.Service.Utils
{
    public class WxToken:BaseDB
    {
        public class Token {
#pragma warning disable IDE1006 // 命名样式
            public string? access_token { get; set; }
            public string? expires_in { get; set; }
#pragma warning restore IDE1006 // 命名样式
        }
        async public Task<string> GetToken() {

            try
            {
                db.BeginTran();
                var tokenList = db.Queryable<RYD_FieldDict>().Where(res => res.RYD_FieldName == "wxToken"&&res.RYD_State==1).ToList();
                var token = tokenList.FirstOrDefault();
                if (token != null)
                {
                    long nowTime = DateTimeHelpUtil.ConvertToTimeStamp(DateTime.UtcNow);

                    long wxTokenTime = DateTimeHelpUtil.ConvertToTimeStamp(Convert.ToDateTime(token.RYD_ModifyTime)) + Convert.ToInt64(token.RYD_FieldText)-200;
                    if (wxTokenTime > nowTime)
                    {
                        db.CommitTran();
                        return token.RYD_FieldValue;
                    }
                }
                string appid = AppHelper.ReadAppSettings("appid");
                string secret = AppHelper.ReadAppSettings("secret");
                //WX接口地址，通过appid和secret密码获取到token
                string wx_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret ;

                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, wx_url);
                var httpClient = HttpClientFactory.Create();

                //发送请求
                var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
                //判断请求是否成功
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    //获取数据流
                    using var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync();
                    var headersStream = httpResponseMessage.Headers.Date;
                    //转换成string
                    StreamReader reader = new(contentStream);
                    string text = reader.ReadToEnd();
                    if (text.Contains("errcode", StringComparison.CurrentCulture))
                    {
                        return "";
                    }
                    //转换成实体
                    Token? tokenStr = JsonHelpUtil.JsonDeserialize<Token>(text);
                    if (tokenStr != null)
                    {
                        if (token == null)
                        {
                            token = new RYD_FieldDict
                            {
                                RYD_Id = Guid.NewGuid().ToString(),
                                RYD_FieldName = "wxToken",
                                RYD_State = 1,
                                RYD_CreateTime = DateTime.Now
                            };
                            db.Insertable(token).ExecuteCommand();
                        }
#pragma warning disable CS8601 // 引用类型赋值可能为 null。
                        token.RYD_FieldValue = tokenStr.access_token;
                        token.RYD_FieldText = tokenStr.expires_in;
#pragma warning restore CS8601 // 引用类型赋值可能为 null。

#pragma warning disable CS8629 // 可为 null 的值类型可为 null。
                        token.RYD_ModifyTime =headersStream.Value.DateTime;
#pragma warning restore CS8629 // 可为 null 的值类型可为 null。

                        db.Updateable(token).ExecuteCommand();
                        db.CommitTran();
                        return tokenStr.access_token??"";

                    }
                }
                return "";

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return "";
            }
        }
    }
}
